<template>
  <div class="view-account">
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="view-account-top-title">基础后台管理系统</div>
        <div class="view-account-top-desc">欢迎使用基础后台管理系统</div>
      </div>
      <div class="view-account-form">
        <a-form ref="loginFormRef" size="large" :model="loginForm" :rules="rules">
          <a-form-item name="username">
            <a-input v-model:value="loginForm.username" allow-clear placeholder="请输入用户名">
              <template #prefix>
                <user-outlined :style="{ color: '#808695' }" />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item name="password">
            <a-input-password
              v-model:value="loginForm.password"
              allow-clear
              placeholder="请输入密码"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <lock-outlined :style="{ color: '#808695' }" />
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item name="captcha" v-if="!isMock">
            <div class="flex justify-between align-center">
              <a-input
                v-model:value="loginForm.captcha"
                placeholder="请输入验证码"
                @keyup.enter="handleLogin"
                class="flex-1 mr-2"
              />
              <a-image
                v-if="captchaUrl"
                :width="76"
                :height="38"
                class="cursor-pointer"
                alt="验证码图片"
                :src="captchaUrl"
                :preview="false"
                @click="getCaptcha"
              />
            </div>
          </a-form-item>
          <a-form-item class="default-color">
            <a-checkbox v-model:checked="autoLogin">自动登录</a-checkbox>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleLogin" size="large" :loading="loading" block>
              登录
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch } from 'vue';
  import { useUserStore } from '@/store/useUserStore';
  import { useRoute, useRouter } from 'vue-router';
  import { LockOutlined, UserOutlined } from '@ant-design/icons-vue';
  import { captcha } from '@/api/UserApi';
  import { Rule } from 'ant-design-vue/es/form';

  const isMock = import.meta.env.VITE_USE_MOCK === 'true';
  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const loginForm = reactive<LoginForm>({
    username: 'admin',
    password: '123456',
    captcha: '',
    captchaId:'',
  });
  const loginFormRef = ref();
  const loading = ref(false);
  const redirect = ref();
  const rules: Record<string, Rule[]> = {
    username: [{ required: true, trigger: 'blur', message: '账号不能为空' }],
    password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
  };
  let otherQuery = {};
  const autoLogin = ref(true);

  watch(
    route,
    (route) => {
      const query = route.query;
      if (query) {
        redirect.value = query.redirect;
        otherQuery = getOtherQuery(query);
      }
    },
    { immediate: true }
  );

  function handleLogin() {
    loginFormRef.value
      .validate()
      .then(() => {
        loading.value = true;
        userStore
          .login(loginForm)
          .then(() => {
            router.push({ path: redirect.value || '/', query: otherQuery });
          })
          .catch(() => {
            loginForm.captcha = '';
            getCaptcha();
          })
          .finally(() => {
            loading.value = false;
          });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  onMounted(() => {
    !isMock && getCaptcha();
  });

  const captchaUrl = ref('');

  function getCaptcha() {
    captcha().then((res) => {
      const captcha = res.data[0]
      captchaUrl.value ="data:image/gif;base64,"+ captcha.captcha;
      loginForm.captchaId =captcha.captchaId;
    });
  }

  function getOtherQuery(query: any) {
    return Object.keys(query).reduce((acc: any, cur) => {
      if (cur !== 'redirect') {
        acc[cur] = query[cur];
      }
      return acc;
    }, {});
  }
</script>

<style scoped lang="less">
  .view-account {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;

    &-container {
      flex: 1;
      padding: 32px 0;
      width: 380px;
      margin: 0 auto;
    }

    &-top {
      padding: 32px 0;
      text-align: center;

      &-title {
        font-size: 44px;
        color: #28313b;
        margin-bottom: 20px;
      }

      &-desc {
        font-size: 14px;
        color: #808695;
      }
    }

    .default-color {
      color: #515a6e;
    }
  }

  @media (min-width: 768px) {
    .view-account {
      background-image: url('../assets/login/login.svg');
      background-repeat: no-repeat;
      background-position: 50%;
      background-size: 100%;
    }
  }
</style>
